#require 'rubygems'
require 'flickr'
require 'JournalXMLib'

MY_APPLICATION_KEY = '1144e0b4b949428c5ed19dea103c5a28'
MY_SECRET = '9aefd3d349e8e92b'

class Uploader
	
	def initialize(token_file)
		@flickr = Flickr.new(token_file, MY_APPLICATION_KEY, MY_SECRET)
		unless @flickr.auth.token
			@flickr.auth.getFrob
			url = @flickr.auth.login_link
			puts "Please visit the following link: \n    #{url}\n and log in, so that this program may have permission to access your account."+
			"You only need to do this once. When you are finished, press the \'Enter\' key to continue."
			gets
			@flickr.auth.getToken
			@flickr.auth.cache_token
		end
	end
	
	def uploadPhotos(destination)
		photos = []
		destination.photos.each do |photo|
			title = destination.name.nameElement[0].to_s + " - " + photo.datetaken.datetakenElement[0].to_s
			description = title + "\n" + destination.city.cityElement[0].to_s \
			+ "Location: " + ", " + destination.country.countryElement[0].to_s \
			+ "\n" + destination.deststartdate.deststartdateElement[0].to_s \
			+ "-" + destination.destenddate.destenddateElement[0].to_s \
			+ "\n" + photo.comment.commentElement[0].to_s \
			+ "\nDate taken: " + destination.photos[0].datetaken.datetakenElement[0].to_s
			filename = destination.photos[0].url.urlElement[0].to_s
			#need to think about creating groups and stuff.
			uploader = Flickr::Upload.new(@flickr)
			if(photo.id.idElement[0].to_s != "0") then
				pid = photo.id.idElement[0].to_s
				photodel = Flickr::Photos.new(@flickr)
				photodel.delete(pid)
			end
			photo_id = uploader.upload_file(filename, title, description)
			photo.id = photo_id
			photos.push(photo_id)
		end
		return photos
	end
	
	def uploadJournal(myJournal)
		myJournal.trips.each do |trip|
			#upload the photos
			photo_ids = []
			trip.destinations.each do |destination|
				photo_ids += uploadPhotos(destination)
			end
			#create the photoset and add the photos to it
			title = trip.name.nameElement[0].to_s
			description = title + "\n Date: " + trip.tripstartdate.tripstartdateElement[0].to_s \
			+ "-" + trip.tripenddate.tripenddateElement[0].to_s
			primary_photo = photo_ids[0].to_s
			photo_ids.delete(primary_photo)
			myPhotoSet = Flickr::PhotoSets.new(@flickr)
			photoset = myPhotoSet.create(title, primary_photo, description)
			photo_ids.each do |photo|
				myPhotoSet.addPhoto(photoset,photo)
			end
		end
	end
end
